package com.uvnos4j.matilda.commons.utils;

import cn.hutool.json.JSONUtil;
import com.uvnos4j.matilda.commons.dto.Result;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * 响应处理工具类
 * <p>
 * Description:响应处理工具类
 * </p>
 *
 * @author Guo.wl
 * @version v1.0.0
 * @see com.uvnos4j.matilda.commons.utils
 * @since 2020-08-31 22:39:18
 */
public class ResponseUtil {

    /**
     * Spring MVC 重定向
     *
     * @param requestUri requestUri
     * @return 重定向路径
     */
    public static String redirect(String requestUri) {
        return "redirect:" + requestUri;
    }

    /**
     * 获取 HttpServletResponse
     *
     * @return response
     */
    public static HttpServletResponse getHttpServletResponse() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        assert requestAttributes != null;
        return requestAttributes.getResponse();
    }

    /**
     * 响应 JSON 消息
     *
     * @param msg 消息
     */
    public static void writeJson(String msg) {
        HttpServletResponse httpServletResponse = getHttpServletResponse();
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        try {
            httpServletResponse.getWriter().write(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 响应 JSON 消息
     *
     * @param result 响应结果
     */
    public static void writeJson(Result result) {
        writeJson(JSONUtil.toJsonStr(result));
    }

    /**
     * 下载
     *
     * @param filePath 要下载的文件路径
     * @param realName 浏览器要保存的文件名
     */
    public static void download(String filePath, String realName) {
        // ResourceUtils.getURL("classpath:").getPath() + "static/files"
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            HttpServletResponse response = getHttpServletResponse();
            long fileLength = new File(filePath).length();

            response.setContentType("application/octet-stream;charset=GBK");
            response.setHeader("Content-disposition",
                    "attachment; filename=" + new String(realName.getBytes("GB2312"), StandardCharsets.ISO_8859_1));
            response.setHeader("Content-Length", String.valueOf(fileLength));

            bis = new BufferedInputStream(new FileInputStream(filePath));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    //
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    //
                }
            }
        }
    }

}